package com.sunlee.admin.api.module.mall.controller;

import com.sunlee.common.core.constant.Constant;
import com.sunlee.common.core.entity.PageData;
import com.sunlee.common.core.entity.Result;
import com.sunlee.common.core.enums.ErrorCodeEnum;
import com.sunlee.common.core.exception.BusinessException;
import com.sunlee.common.core.utils.StringUtil;
import com.sunlee.common.service.dto.MarketingProductInfoDTO;
import com.sunlee.common.service.entity.MarketingProductMappingEntity;
import com.sunlee.common.service.service.MarketingProductMappingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author sunjulei
 * @date 2022/6/27
 */
@RestController
@RequestMapping("/marketingProduct")
@Api(tags = "营销商品映射表")
public class MarketingProductController {

    @Autowired
    private MarketingProductMappingService service;

    /**
     * 分页查询可关联 或 已关联商品
     *
     * @param params
     * @return
     */
    @GetMapping("/relatedProduct/page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = Constant.ID, value = "分类ID", paramType = "query", required = true, dataType = "long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = Constant.TYPE, value = "查询类型：1已关联、0未关联", paramType = "query", required = true, dataType = "int", dataTypeClass = Integer.class)
    })
    @RequiresPermissions("marketing:page")
    public Result<PageData<MarketingProductInfoDTO>> pageRelatedProduct(@ApiIgnore @RequestParam Map<String, Object> params) {

        long id = Long.parseLong((String) params.getOrDefault(Constant.ID, "0"));
        if (id <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }

        int type = Integer.parseInt((String) params.getOrDefault(Constant.TYPE, "0"));

        String title = (String) params.getOrDefault(Constant.TITLE, "");

        String pIdStr = (String) params.get(Constant.PID);
        Long pId = null;
        if (StringUtils.isNotBlank(pIdStr)) {
            pId = Long.valueOf(pIdStr);
        }


        return Result.ok(service.pageRelatedProduct(params, id, pId, title, type));
    }

    @PostMapping("/save/{marketingId}")
    @RequiresPermissions("marketing:save")
    public Result<Object> save(@PathVariable("marketingId") Long marketingId,
                               @RequestBody Long[] ids) {

        if (marketingId == null || marketingId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }
        List<MarketingProductMappingEntity> saveEntityList = Arrays.stream(ids).map(pId -> {
            MarketingProductMappingEntity entity = new MarketingProductMappingEntity();
            entity.setMarketingId(marketingId);
            entity.setProductId(pId);
            return entity;
        }).collect(Collectors.toList());

        service.insertBatchOwn(saveEntityList);
        return Result.ok();
    }

    @PostMapping("/delete/{marketingId}")
    @RequiresPermissions("marketing:save")
    public Result<Object> delete(@PathVariable("marketingId") Long marketingId,
                                 @RequestBody Long[] ids) {

        if (marketingId == null || marketingId <= 0) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }

        return Result.ok(service.deleteByPIdAndCId(marketingId, ids));
    }

    @PostMapping("/updateSort/{id}/{sort}")
    @RequiresPermissions("marketing:save")
    public Result<Boolean> updateSort(@PathVariable("id") Long id, @PathVariable("sort") Integer sort) {

        if (id == null || id <= 0 || sort == null) {
            throw new BusinessException(ErrorCodeEnum.MISSING_CATEGORY_ID);
        }
        return Result.ok(service.updateSort(id, sort));
    }
}
